﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using CoolCode.Web.Mvc.UI;

namespace CoolCode.Web.Mvc 
{
    public static  class ScriptExtensions
    {
        private static readonly string Key = typeof(ViewComponentFactory).AssemblyQualifiedName;

        /// <summary>
        /// Gets the CoolCode View Component Factory
        /// </summary>
        /// <param name="helper">The helper.</param>
        /// <returns>The Factory</returns>
        public static ViewComponentFactory CoolCode(this HtmlHelper helper)
        {
            Guard.IsNotNull(helper, "helper");

            ViewContext viewContext = helper.ViewContext;
            HttpContextBase httpContext = viewContext.HttpContext;
            ViewComponentFactory factory = httpContext.Items[Key] as ViewComponentFactory;

            if (factory == null)
            {
                IServiceLocator locator = ServiceLocator.Current;

                IWebAssetItemMerger assetItemMerger = locator.Resolve<IWebAssetItemMerger>();
                ScriptWrapperBase scriptWrapper = locator.Resolve<ScriptWrapperBase>();
                IClientSideObjectWriterFactory clientSideObjectWriterFactory = locator.Resolve<IClientSideObjectWriterFactory>();

                StyleSheetRegistrar styleSheetRegistrar = new StyleSheetRegistrar(new WebAssetItemCollection(WebAssetDefaultSettings.StyleSheetFilesPath), viewContext, assetItemMerger);
                ScriptRegistrar scriptRegistrar = new ScriptRegistrar(new WebAssetItemCollection(WebAssetDefaultSettings.ScriptFilesPath), new List<IScriptableComponent>(), viewContext, assetItemMerger, scriptWrapper);

                StyleSheetRegistrarBuilder styleSheetRegistrarBuilder = new StyleSheetRegistrarBuilder(styleSheetRegistrar);
                ScriptRegistrarBuilder scriptRegistrarBuilder = new ScriptRegistrarBuilder(scriptRegistrar);

                factory = new ViewComponentFactory(helper, clientSideObjectWriterFactory, styleSheetRegistrarBuilder, scriptRegistrarBuilder);

                helper.ViewContext.HttpContext.Items[Key] = factory;
            }

            return factory;
        }
    }
}
